function [newX]=findValley(P,R,sites, edges, siteGrid)
%findValley(P,R,sites) find the sites between P and R that can possibly
%avoid high peaks in-between.

% %pick sites that are within rectangle whose diagonal defined by P-R
% numSites=size(sites,1);
% S_inside=[];
% A=P(1:2);
% C=R(1:2);
% B1=[P(1); R(2)];
% B2=[R(1); P(2)];
% 
% for site=1:numSites
%     if insideTriangle(A,B1,C, sites(site,1:2)') || insideTriangle(A,B2,C, sites(site,1:2)')
%         S_inside=[S_inside; site];
%     end
% end


[x_idx, y_idx]=findIdx([P(1); R(1)], [P(2); R(2)], siteGrid);
[BBox_x, BBox_y]=meshgrid(min(x_idx):1:max(x_idx),min(y_idx):1:max(y_idx));
theLength=size(BBox_x,1)*size(BBox_x,2);
S_inside=[];
for l=1:theLength
    S_inside=[S_inside, siteGrid.grid{BBox_x(l), BBox_y(l)}];
end
S_inside=S_inside';


%find the valley (lowest height)
idx=find(sites(S_inside,3)==min(sites(S_inside,3)));
candidates=S_inside(idx);

%find the sites that are connected to the low heights...
count=zeros(size(candidates));
height=zeros(size(candidates));
numEdges=size(edges,1);
for e=1:numEdges
    if ~isempty(intersect(edges(e,1),candidates))
        idx=find(candidates==edges(e,1));
        count(idx)=count(idx)+1;
        height(idx)=height(idx)+sites(edges(e,1),3);
    end
    if ~isempty(intersect(edges(e,2),candidates))
        idx=find(candidates==edges(e,2));
        count(idx)=count(idx)+1;
        height(idx)=height(idx)+sites(edges(e,2),3);
    end
end
average=height./count;
[val idx]=min(average);

theCandidate=candidates(idx);
newX=sites(theCandidate,:)';

return;